package com.ratingbay.console.restful.view;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.ServletOutputStream;

import org.springframework.web.servlet.view.JstlView;

public class RestfulResponseWrapper extends HttpServletResponseWrapper {

    private class RestfulOutPutStream extends ServletOutputStream {
        ByteArrayOutputStream byteArrayOutStream;
        public RestfulOutPutStream(ByteArrayOutputStream servletOutputStream) {
            this.byteArrayOutStream = servletOutputStream;
        }

        @Override
        public void write(int buffer) throws IOException {
            this.byteArrayOutStream.write(buffer);
        }
    }


    //public method
    public String getContent() throws IOException {
        this.flushContentBuffer();
        return this._contentBuffer.toString("UTF-8");
    }

    public void flushContentBuffer() throws IOException {
        if(null != this.servletOutputStream) {
            this.servletOutputStream.flush();
        }
        if(null != this.printWriter) {
            this.printWriter.flush();
        }
    }

    
    private ByteArrayOutputStream _contentBuffer;


    //extend method
    private PrintWriter printWriter = null;
    private ServletOutputStream servletOutputStream = null;

    public RestfulResponseWrapper(HttpServletResponse response)
        throws UnsupportedEncodingException {

        super(response);
        this._contentBuffer = new ByteArrayOutputStream();
        this.servletOutputStream = new RestfulOutPutStream(this._contentBuffer);
        this.printWriter = new PrintWriter(new OutputStreamWriter(this._contentBuffer, "UTF-8"));

    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return this.servletOutputStream;
    }

    @Override
    public PrintWriter getWriter() throws UnsupportedEncodingException {
        return this.printWriter;
    }
}